package com.jijs.soap.handler;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import javax.xml.ws.soap.SOAPFaultException;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class LicenseHandler implements SOAPHandler<SOAPMessageContext>{

	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		try{
			String ns = "http://www.infcn.com.cn/";
			Boolean out = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
			if(!out){
				SOAPMessage message = context.getMessage();
				SOAPEnvelope enve = message.getSOAPPart().getEnvelope();
				SOAPHeader header = enve.getHeader();
				SOAPBody body = enve.getBody();
				//获取partname，也就是方法名
				//<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:login xmlns:ns2="http://www.infcn.com.cn/"><userName xmlns="">admin</userName><password xmlns="">123456</password></ns2:login></S:Body></S:Envelope>
				Node bn = body.getChildNodes().item(0);
				String partname = bn.getLocalName();
				System.out.println("调用的方法名"+partname);
				//如果是list或addUser方法就做验证
				if("list".equals(partname)||"addUser".equals(partname)){
					if(header==null){
						//添加一个错误信息
						SOAPFault fault = body.getFault();
						if(fault==null){
							fault = body.addFault();
						}
						fault.setFaultString("头信息不能为空！");
						throw new SOAPFaultException(fault);
					}
					Iterator<SOAPHeaderElement> iterator = header.extractAllHeaderElements();
					if(!iterator.hasNext()){
						//添加一个错误信息
						System.out.println("ttt");
						SOAPFault fault = body.addFault();
						fault.setFaultString("头部信息不正确");
						throw new SOAPFaultException(fault);
					}
					while(iterator.hasNext()){
						SOAPHeaderElement ele = iterator.next();
						System.out.println(ele.getTextContent());
					}
				}
			}
		} catch(SOAPException e){
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		System.out.println("error");
		return false;
	}

	@Override
	public void close(MessageContext context) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Set<QName> getHeaders() {
		// TODO Auto-generated method stub
		return null;
	}
	

}
